import { View } from '@tarojs/components'
import { memo, useEffect, useState, useCallback } from 'react'
import BtLayout from '@/BtComponents/BtLayout'
import { useLoad } from '@tarojs/taro'
import utils from '@/utils'
import BtScroll from '@/BtComponents/BtScroll'
import Search from './components/Search'
import Tabs from './components/Tabs'
import Filter from './components/Filter'
import StaffQrcodeCell from './components/StaffQrcodeCell'
import GroupQrcodeCell from './components/GroupQrcodeCell'
import useActivityQrcodeStore, {
  setStaffList,
  setGroupList,
  setPagination,
  setIsMore,
  setFirstLoaded
} from './useActivityQrcodeStore'
import { QrcodeTabEnum, QrcodeListParams, StaffQrcode, GroupQrcode } from './interface'
import './index.scss'
import { mockGetQrcodeList } from './mock'
import Empty from './components/Empty'

/**
 * 活码页面
 * @description 包含员工活码和客户群活码两个tab，支持搜索、筛选、下拉刷新和上拉加载
 */
function ActivityQrcodePage() {
  // 从store中获取状态
  const currentTab = useActivityQrcodeStore(state => state.currentTab) // 当前tab
  const status = useActivityQrcodeStore(state => state.status) // 当前状态（我的/团队）
  const filter = useActivityQrcodeStore(state => state.filter) // 筛选条件
  const staffList = useActivityQrcodeStore(state => state.staffList) // 员工活码列表
  const groupList = useActivityQrcodeStore(state => state.groupList) // 客户群活码列表
  const page = useActivityQrcodeStore(state => state.page) // 当前页码
  const pageSize = useActivityQrcodeStore(state => state.pageSize) // 每页数量
  const isMore = useActivityQrcodeStore(state => state.isMore) // 是否还有更多数据
  const firstLoaded = useActivityQrcodeStore(state => state.firstLoaded)
  // 本地状态
  const [refreshing, setRefreshing] = useState(false) // 是否正在刷新
  const [isInited, setIsInited] = useState(false) // 页面是否已初始化

  /**
   * 获取列表请求参数
   * @returns {QrcodeListParams} 请求参数
   */
  const getParams = () => ({
    page,
    pageSize,
    status,
    tab: currentTab,
    filter
  })

  /**
   * 获取列表数据
   * @param {QrcodeListParams} params - 请求参数
   */
  const fetchList = async (params: QrcodeListParams) => {
    try {
      const res: any = await mockGetQrcodeList(params)
      // 根据当前tab处理不同类型的列表数据
      if (params.tab === QrcodeTabEnum.STAFF) {
        const list = params.page === 1 ? res.data.list : [...staffList, ...res.data.list]
        const pageIsMore = list.length < res.data.total
        setStaffList(list as StaffQrcode[])
        setIsMore(pageIsMore)
      } else {
        const list = params.page === 1 ? res.data.list : [...groupList, ...res.data.list]
        const pageIsMore = list.length < res.data.total
        setGroupList(list as GroupQrcode[])
        setIsMore(pageIsMore)
      }

      // 更新分页信息
      setPagination(params.page, res.data.total)
      setFirstLoaded(true)
      // 延迟重置刷新状态，确保动画流畅
      setTimeout(() => {
        setRefreshing(false)
      }, 50)
    } catch (error) {
      console.error('获取列表失败:', error)
      setRefreshing(false)
    }
  }

  /**
   * 监听状态变化，重新获取数据
   */
  useEffect(() => {
    if (!isInited) return
    const params = getParams()
    fetchList(params)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, currentTab, filter, page, pageSize, isInited])

  /**
   * 页面首次加载
   */
  useLoad(async () => {
    try {
      await utils.$initPage()
      setIsInited(true)
    } catch (error) {
      console.error('页面初始化失败:', error)
    }
  })

  /**
   * 处理下拉刷新
   */
  const handleRefresh = async () => {
    try {
      setRefreshing(true)
      setPagination(1)
      if (page === 1) {
        await fetchList(getParams())
      }
    } catch (error) {
      console.error('刷新失败:', error)
      setRefreshing(false)
    }
  }

  /**
   * 处理上拉加载更多
   */
  const handleLoadMore = useCallback(async () => {
    if (!isMore) return
    setPagination(page + 1)
  }, [isMore, page])

  return (
    <BtLayout
      config={{
        title: '活码',
      }}
    >
      <View className='qrcode-container'>
        {/* 头部区域：搜索、Tab切换、筛选 */}
        <Search />
        <Tabs />
        <Filter />
        {/* 内容区域：列表 */}
        <BtScroll
          onRefresh={handleRefresh}
          onLoadMore={handleLoadMore}
          refresherTriggered={refreshing}
        >
          {/* 根据当前tab渲染员工活码or群活码 */}
          <View className='list'>
            {currentTab === QrcodeTabEnum.STAFF ? (
              staffList.length > 0 ? (
                staffList.map((item, index) => (
                  <StaffQrcodeCell key={index} data={item} />
                ))
              ) : (
                firstLoaded ? <Empty tab={QrcodeTabEnum.STAFF} /> : null
              )
            ) : (
              groupList.length > 0 ? (
                groupList.map((item, index) => (
                  <GroupQrcodeCell key={index} data={item} />
                ))
              ) : (
                firstLoaded ? <Empty tab={QrcodeTabEnum.STAFF} /> : null
              )
            )}
          </View>
        </BtScroll>
      </View>
    </BtLayout>
  )
}

export default memo(ActivityQrcodePage)
